/*
	Description: We don't use a fixed key as in previous example. We generate the key.
	This process uses a known "key" to get access to a shared memory segment 
	allocated by some other process. Once we get a "memory segment identifier" we can 
	"attach it" to our virtual memory space in order to access it as normal memory, as a result 
	we'll have a memory pointer which can be used as an array name.

	Author: Hugo Mendez @ ITESM CCV Sep 2011
*/


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <string.h>

int main (int argc, const char * argv[]) {
	//Let's generate the "key", in the same way as the "creator" did it	
	key_t key; 
	key=ftok("shmCreator.c", '1');

  //Let's get access to the segment memory numbered "key"
  int segment_id = shmget(key, getpagesize(), 0666);
  
  //Check for problems
  if(segment_id < 0){
   printf("Problemas al solicitar el segmento de memoria");
    exit(1);
  }
  printf("segment_id: %d\n", segment_id);
  
  //Let's attach the memory segment to our address space in order to use it
  //Where in our address space are we going to attach it? Let Linux find it out
  char *shm;      //We need a byte pointer to have access to the shared memory segment
  shm = shmat(segment_id, NULL, 0);
  
  //Let's read an string from the shared memory
  //Some process should have written something!
  printf("%s\n", shm);
  
  //Write the '*', at location 0, our Creator program is waiting for
  shm[0]='*';
  
  //Detach the memory segment
  shmdt(segment_id);
  
	return 0;  
}

